package com.easyattendance.servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.easyattendance.model.AttendanceTakenBy;
import com.easyattendance.model.EmailSettings;
import com.easyattendance.model.Parent;
import com.easyattendance.model.StudentAttendance;
import com.easyattendance.model.SubjectClass;
import com.easyattendance.model.Teacher;
import com.easyattendance.services.AddClassService;
import com.easyattendance.services.AddStudentService;
import com.easyattendance.services.AddSubjectService;
import com.easyattendance.services.AddTeacherService;
import com.easyattendance.services.AttendanceSubmissionService;

@WebServlet(name = "AttendanceSubmissionServlet", urlPatterns = "/AttendanceSubmissionServlet")
public class AttendanceSubmissionServlet extends HttpServlet {

	protected void processRequest(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		
		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		
		 HttpSession session = null;
		 Teacher teacher=new Teacher();
		AddStudentService addStudentService = new AddStudentService();
		
		AddTeacherService addTeacherService=new AddTeacherService();
		String sectionEmail=null,class_id=null;
		String msg=null,email_id = null, password=null;
		
		if(request.getParameter("section_email")!=null)
				sectionEmail=request.getParameter("section_email");
		AttendanceSubmissionService attendanceService=new AttendanceSubmissionService();
		EmailSettings mail_info=attendanceService.getEmailSettingsBySectionEmailId(sectionEmail);
		
		if(mail_info!=null)
		{
			 msg=mail_info.getSend_email_msg();
			 email_id=mail_info.getSend_email_id();
			 password=mail_info.getSend_email_pass();
		}
		
		String stud_id[] =request.getParameterValues("stud_roll_no");
		String status[] = new String[stud_id.length];
		
		if(request.getParameter("class_id")!=null)
			class_id=request.getParameter("class_id");
	
		for (int i = 0; i < stud_id.length; i++) {
			if(request.getParameter("status" + i) != null) {
				status[i] = request.getParameter("status" + i);
			}
			else
				status[i]="";

			if (status[i].equals("present"))
				status[i] = "P";
			else if (status[i].equals("absent"))
			{
				status[i] = "A";
				Parent parent=attendanceService.getParentByStudentId(stud_id[i], class_id);
				boolean IsMailSent=attendanceService.SendMail(email_id,password,msg,parent);
			}
			else if(status[i].equals("leave"))
				status[i] = "L";
			else if(status[i].equals(""))
				status[i]="P";
		}

		AttendanceSubmissionService submitservice = new AttendanceSubmissionService();

		int id = 0;
		Date attendance_date = null;
		String status_str = null;
		
		boolean result = false;
		for (int i = 0; i < stud_id.length; i++) {
			result = false;
			id = Integer.parseInt(stud_id[i]);
			//student = addStudentService.getStudentByStudentRollNo(id);
			attendance_date = new Date();
			status_str = status[i];
			

			StudentAttendance attendance_obj = new StudentAttendance(id,class_id,attendance_date,status_str);
			
			
			if (!submitservice.ifAlreadyExists(attendance_obj)) {
				result = submitservice.saveAttendance(attendance_obj);
			}
			else {
				//out.println("Today's attendance already exists");
				request.setAttribute("attendanceExists", "Today's attendance already exists");
	        	RequestDispatcher rd = request.getRequestDispatcher("views/teacher/viewAttendanceStudentList.jsp");
	        	rd.forward(request, response);
			}

			if (result == false) {
				break;
			}

		}
		if(result){
			// Save records in attendance takenby table
			java.sql.Date date=new java.sql.Date(new Date().getTime());
			String teacher_id=null;
			
			if(request.getParameter("teacher_id")!=null)
				teacher_id=request.getParameter("teacher_id");
			
			boolean result2=false;
			
			AttendanceTakenBy attendance_detail=new AttendanceTakenBy(date,class_id,teacher_id);
			if (!submitservice.ifDetailsAlreadyExists(attendance_detail)) {
				result2 = submitservice.saveAttendanceTakenBy(attendance_detail);
			}
			else {
				//out.println("Today's attendance  details already exists");
				request.setAttribute("attendanceExists", "Today's attendance already exists");
	        	RequestDispatcher rd = request.getRequestDispatcher("views/teacher/viewAttendanceStudentList.jsp");
	        	rd.forward(request, response);
			}

			
			try {
				if (result && result2) {
					//out.println("<h1>Attendance details saved Successfully</h1>");
					
					/* Increment counter in teacher_subject table for attendance date */
		    		AddTeacherService teacherService = new AddTeacherService();
		    		String classId = request.getParameter("class_id");
		    		AddClassService classService = new AddClassService();
		    		teacherService.incrementLectureStatus( classService.getClassById(classId).getSection().getEmail_id() , classId);
		    		
		    		/* Increment counter in subject_class table for attendance date */
		    		AddSubjectService subjectService = new AddSubjectService();
		    		subjectService.incrementLectureStatus(classService.getClassById(classId).getSection().getEmail_id(), classId);
					
					request.setAttribute("attendanceSaved", "Attendance details saved Successfully");
		        	RequestDispatcher rd = request.getRequestDispatcher("views/teacher/viewAttendanceStudentList.jsp");
		        	rd.forward(request, response);
				} else {
					//out.println("<h1>Attendance could not be saved successfully </h1>");
					request.setAttribute("attendanceNotSaved", "Attendance could not be saved successfully");
		        	RequestDispatcher rd = request.getRequestDispatcher("views/teacher/viewAttendanceStudentList.jsp");
		        	rd.forward(request, response);
				}
			} finally {
			}
		}
		

	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}
}
